<template>
  <div>
    <!-- 导航 -->
    <van-nav-bar title="修改资料" left-arrow @click-left="$router.back()" />
    <!-- 头像 -->
    <div class="avatar-box">
      <van-image fit="cover" round :src="userInfo.photo" />
      <van-uploader :after-read="afterRead" />
    </div>
    <!-- cell区域 -->
    <van-cell-group>
      <van-cell
        @click="clickName"
        title="名称"
        :value="userInfo.name"
        is-link
      />
      <van-cell
        @click="genderShow = true"
        title="性别"
        :value="userInfo.gender ? '女' : '男'"
        is-link
      />
      <van-cell
        @click="clickBirth"
        title="生日"
        :value="userInfo.birthday"
        is-link
      />
    </van-cell-group>
    <!-- 裁剪区域盒子 -->
    <div v-show="cropShow" class="crop-box">
      <vueCropper
        ref="cropper"
        :img="cropImg"
        autoCrop
        autoCropWidth="200"
        autoCropHeight="200"
      ></vueCropper>
      <van-button @click="doCrop" style="left: 0" type="primary" size="small"
        >裁剪</van-button
      >
      <van-button
        @click="cropShow = false"
        style="right: 0"
        type="primary"
        size="small"
        >取消</van-button
      >
    </div>
    <!-- 修改资料 -->
    <van-dialog
      @confirm="changeName"
      v-model="nameShow"
      title="修改昵称"
      show-cancel-button
    >
      <van-field ref="ipt" style="border: 1px solid #ddd" v-model="editName" />
    </van-dialog>
    <!-- 修改性别 -->
    <van-popup
      v-model="genderShow"
      position="bottom"
      :style="{ height: '30%' }"
    >
      <van-picker
        title="修改性别"
        show-toolbar
        :columns="columns"
        @confirm="changeGender"
        @cancel="genderShow = false"
      />
    </van-popup>
    <!-- 修改生日 -->
    <van-popup v-model="birthShow" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker
        @confirm="changeBirth"
        @cancel="birthShow = false"
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { VueCropper } from 'vue-cropper'
import { avatarAPI, editUserAPI } from '@/api/user'
import { Toast } from 'vant'
import user from '@/store/modules/user'
import dayjs from 'dayjs'

export default {
  data () {
    return {
      cropShow: false,
      cropImg: '',
      nameShow: false,
      editName: '',
      genderShow: false,
      columns: ['男', '女'],
      birthShow: false,
      minDate: new Date(1949, 9, 1),
      maxDate: new Date(),
      currentDate: new Date(2021, 0, 17)
    }
  },
  components: {
    VueCropper
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  created () {
    this.$store.dispatch('user/reqUserInfo')
  },
  methods: {
    afterRead (file) {
      // 此时可以自行将文件上传至服务器
      // console.log(file)
      // 显示出裁剪框
      this.cropShow = true
      // 把选中的图片的base64给到裁剪插件
      this.cropImg = file.content
    },
    doCrop () {
      // 点击获取截图内容  blob获取的是对象类型
      this.$refs.cropper.getCropBlob(async data => {
        // console.log(data)
        // 把获取到的内容上传到接口
        // ajax上传文件 必须用FormData才能传递
        const tx = new FormData()
        tx.append('photo', data)
        const res = await avatarAPI(tx)
        // console.log(res)
        // 隐藏裁剪框
        this.cropShow = false
        // 把上传之后的数据再渲染页面
        this.$store.commit('user/setUserInfo', {
          // 把原本的数据展开 不然只有一个数据
          ...this.userInfo,
          photo: res.data.photo
        })
      })
    },
    async clickName () {
      // 1. 显示出弹出框 -- dom渲染是异步的
      this.nameShow = true
      // 2. 把名字渲染到弹出框的输入框
      this.editName = this.userInfo.name
      // 3. 让输入框获得焦点
      // 用$nextTick --> 会等下一次dom更新后调用
      await this.$nextTick()
      this.$refs.ipt.focus()
    },
    async changeName () {
      // 非空判断
      if (this.editName === '') return this.$toast('昵称不能为空')
      await editUserAPI({
        name: this.editName
      })
      // 把修改的数据存到vuex里
      this.$store.commit('user/setUserInfo', {
        ...this.userInfo,
        name: this.editName
      })
    },
    async changeGender (value, index) {
      await editUserAPI({
        gender: String(index)
      })
      // 把修改的数据存到vuex里
      this.$store.commit('user/setUserInfo', {
        ...this.userInfo,
        gender: index
      })
      this.genderShow = false
    },
    clickBirth () {
      this.birthShow = true
      // 赋值生日给日期
      this.currentDate = new Date(this.userInfo.birthday)
    },
    // 修改生日
    async changeBirth () {
      // 1. 隐藏弹出层
      this.birthShow = false
      // 转换成字符串
      const birthday = dayjs(this.currentDate).format('YYYY-MM-DD')
      // 2. 发请求给服务器
      await editUserAPI({
        birthday
      })
      // 3. 修改到vuex
      this.$store.commit('user/setUserInfo', {
        ...this.userInfo,
        birthday
      })
    }
  }
}
</script>

<style lang="less" scoped>
.avatar-box {
  height: 140px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;

  .van-image {
    width: 120px;
    height: 120px;
  }

  .van-uploader {
    position: static;

    ::v-deep .van-uploader__upload {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
    }
  }
}

.crop-box {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;

  .van-button {
    position: fixed;
    bottom: 0;
  }
}
</style>
